/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bm.util;

import com.google.gson.JsonObject;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.DefaultMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 *
 * @author badboy
 */
public class Util {

    public static boolean isNumeric(String str) {
        return str.matches("0?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
    }

    public static String getString(Object str) {
        String ret;

        if (str == null || str.equals("")) {
            ret = "";
        } else {
            ret = str.toString();
        }

        return ret;
    }

    public static int getInt(Object str) {
        int ret = 0;

        if (str == null || str.equals("")) {
            ret = 0;
        } else {
            try {
                ret = Integer.valueOf(str.toString());
            } catch (Exception e) {
                return ret;
            }
        }

        return ret;
    }

    public static String getJSONString(JsonObject jso, String key, String defaultValue) {
        try {
            return (jso.get(key) == null || jso.get(key).getAsString() == null ? defaultValue : jso.get(key).getAsString());
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static String getJSONString(JsonObject jso, String key) {
        return getJSONString(jso, key, "");
    }

    public static String getMonth(String month) {
        HashMap<String, String> jenisMap = new HashMap<String, String>();
        jenisMap.put("january", "01");
        jenisMap.put("february", "02");
        jenisMap.put("march", "03");
        jenisMap.put("april", "04");
        jenisMap.put("may", "05");
        jenisMap.put("june", "06");
        jenisMap.put("july", "07");
        jenisMap.put("august", "08");
        jenisMap.put("september", "09");
        jenisMap.put("october", "10");
        jenisMap.put("november", "11");
        jenisMap.put("december", "12");
        return jenisMap.get(month.toLowerCase());
    }

    public static String doRequestWithTimeout(String command, String uri, boolean isPost, int timeout, int retryCount) {
        HttpClient client = new HttpClient();
        
        // timeout
        client.setConnectionTimeout(timeout);
        client.setTimeout(timeout);

        MessagePrinter.printDebug(" Request Command : " + uri + " " + command);

        if (isPost) {
            // retry count
            DefaultMethodRetryHandler retryhandler;
            retryhandler = new DefaultMethodRetryHandler();
            retryhandler.setRetryCount(retryCount);
            client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);

            PostMethod method = new PostMethod(uri);
            
            NameValuePair[] nv = new NameValuePair[]{new NameValuePair("data", command)};
            method.setRequestBody(nv);
            method.setHttp11(true);
            method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            try {

                int returnCode = client.executeMethod(method);

                if (returnCode != HttpStatus.SC_NOT_IMPLEMENTED) {
                    String response = method.getResponseBodyAsString();
                    MessagePrinter.printDebug(" Server Response : " + response);
                    return response;
                }
            } catch (Exception e) {
                return "";
            } finally {
                method.releaseConnection();
            }
        } else {
            GetMethod method = new GetMethod(uri);

            method.setQueryString(command.trim());
            method.setHttp11(true);

            try {
                int returnCode = client.executeMethod(method);

                if (returnCode != HttpStatus.SC_NOT_IMPLEMENTED) {
                    String response = method.getResponseBodyAsString();
                    MessagePrinter.printDebug(" Server Response : " + response);
                    return response;
                }
            } catch (Exception e) {
                MessagePrinter.printDebug(e.getMessage());
            } finally {
                method.releaseConnection();
            }
        }
        return "";
    }

    public static String doRequest(String command, String uri, boolean isPost) {
        return doRequestWithTimeout(command, uri, isPost, 100000, 2);
    }

    public static String stripBeginningZero(String text) {
        return text.replaceFirst("^0+(?!$)", "");
    }

    public static String getMonthName(int month) {
        ArrayList<String> months = new ArrayList<String>();

        months.add("Jan");
        months.add("Feb");
        months.add("Mar");
        months.add("Apr");
        months.add("May");
        months.add("Jun");
        months.add("Jul");
        months.add("Aug");
        months.add("Sep");
        months.add("Oct");
        months.add("Nov");
        months.add("Dec");

        return months.get(month);
    }

    public static String convertNoTelp(String noTelp) {
        return noTelp.substring(0, 3) + "*";
    }

    public static String getFileContent(String url) {
        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();

        // Create a method instance.
        GetMethod method = new GetMethod(url);

        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + method.getStatusLine());
            }

            // Read the response body.
            byte[] responseBody = method.getResponseBody();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            return new String(responseBody);

        } catch (HttpException e) {
            System.err.println("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // Release the connection.
            method.releaseConnection();
        }
        return "";
    }
}
